package sk.bielyvlk.vlkgps;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import sk.bielyvlk.vlkgps.db.DbHelper;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.SQLException;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class VlkGpsService extends Service implements LocationListener {
	public static final String TAG = "vlkGPS.VlkGpsService";
	
	private boolean recording;
	private LocationManager lm;
	
	private boolean sendToWeb = false;
	
	private DbHelper dbHelper = null;
	private long trackId = 0;
	private int sequence;
	
	private final IBinder localBinder = new LocalBinder();
	
	NotificationManager notificationManager;
	Notification notification;
	private static final int NOTIFI_RECORD_ID = 1;
	PendingIntent contentIntent;
	
	private double minDistance = 10.0;
	private double minTime = 10000;

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "service is created");
		try {
			VlkGps.prepareDirectory();
			dbHelper = new DbHelper(this);
			notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			Intent notificationIntent = new Intent(this, VlkGps.class);
			contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
		} catch (Exception e) {
			Log.e(TAG, e.toString());
		}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "service is destroyed");
		if (recording) recordStop();
		dbHelper.close();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return localBinder;
	}
	
	public class LocalBinder extends Binder {
		VlkGpsService getService() {
			return VlkGpsService.this;
		}
	}

	public boolean isRecording() {
		return recording;
	}
	
	public DbHelper getDbHelper() {
		return dbHelper;
	}
	
	public void recordStart(String name) {
		if (recording) return;
		try {
			if (lm == null) lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
			if (lm != null) lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
			recording = true;
			trackId = dbHelper.insertTrack("", "");
			sequence = 0;
			Log.d(TAG, "record started... (trackId: " + trackId + ")");
			notification = new Notification(R.drawable.vlkgpsnotify, "VlkGPS recording", System.currentTimeMillis());
			notification.setLatestEventInfo(getApplicationContext(), "VlkGPS recording", "", contentIntent);
			notificationManager.notify(NOTIFI_RECORD_ID, notification);
		} catch (SQLException e) {
			Log.e(TAG, e.toString());
		}
	}
	
	public void recordStop() {
		if (!recording) return;
		recording = false;
		lm.removeUpdates(this);
		Log.d(TAG, "record stopped...");
		notificationManager.cancel(NOTIFI_RECORD_ID);
		dbHelper.stopTransaction();
	}
	
	public int getSequence() {
		return sequence;
	}

	Location lastLocation = null;

	@Override
	public synchronized void onLocationChanged(Location location) {
		if ((lastLocation != null) && (location.distanceTo(lastLocation) < minDistance) && (location.getTime() < lastLocation.getTime() + minTime)) return;
		lastLocation = new Location(location);
		sequence++;
		notification.setLatestEventInfo(getApplicationContext(), "VlkGPS recording", "recorded points: " + sequence, contentIntent);
		notificationManager.notify(NOTIFI_RECORD_ID, notification);
		dbHelper.insertTrackpoint(trackId, location);
		if (sendToWeb) { 
			try {
				URL url = new URL("http://dev.freemap.sk/api/uls?/123/" + location.getLatitude() + "/" + location.getLongitude());
				Log.d("location ", "sending URL"  + url.toString());
				URLConnection uc = url.openConnection();
				BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
				String inputLine = br.readLine();
				br.close();
				Log.d(TAG, "sending URL Done: " + inputLine);
			} catch (Exception e) {
				Log.e(TAG, e.toString());
			}
		}
	}

	@Override
	public void onProviderDisabled(String provider) {}

	@Override
	public void onProviderEnabled(String provider) {}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {}
	
}
